<template>
  <div class="shop-owner-management">

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-card shadow="never">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <!-- 第一行搜索条件 -->
          <el-form-item label="店铺">
            <el-select 
              v-model="searchForm.shopId" 
              placeholder="请选择店铺" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="业主类型">
            <el-select 
              v-model="searchForm.ownerType" 
              placeholder="请选择业主类型" 
              clearable
              style="width: 150px"
            >
              <el-option label="业主" :value="1" />
              <el-option label="租户" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="业主姓名">
            <el-input 
              v-model="searchForm.ownerName" 
              placeholder="请输入业主姓名" 
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input 
              v-model="searchForm.ownerPhone" 
              placeholder="请输入联系电话" 
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="正常" :value="1" />
              <el-option label="异常" :value="0" />
            </el-select>
          </el-form-item>
          
          <!-- 第二行搜索条件 -->
          <el-form-item label="身份证号">
            <el-input 
              v-model="searchForm.ownerIdCard" 
              placeholder="请输入身份证号" 
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="企业名称">
            <el-input 
              v-model="searchForm.companyName" 
              placeholder="请输入企业名称" 
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input 
              v-model="searchForm.email" 
              placeholder="请输入邮箱" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="请输入关键词搜索" 
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <!-- 第三行搜索条件 -->
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.createTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-card shadow="never">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增业主
          </el-button>
          <el-button type="success" @click="handleExport" :disabled="ownerList.length === 0">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="info" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-card shadow="never">
        <el-table 
          :data="ownerList" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="ownerName" label="业主姓名" width="100" />
          <el-table-column prop="ownerTypeName" label="业主类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.ownerType === 1 ? 'success' : 'primary'">
                {{ row.ownerTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ownerIdCard" label="身份证号" min-width="150">
            <template #default="{ row }">
              {{ maskIdCard(row.ownerIdCard) }}
            </template>
          </el-table-column>
          <el-table-column prop="ownerPhone" label="联系电话" width="130" />
          <el-table-column prop="email" label="邮箱" min-width="150">
            <template #default="{ row }">
              {{ row.email || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="companyName" label="企业名称" min-width="150">
            <template #default="{ row }">
              {{ row.companyName || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="statusName" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-card shadow="never">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 业主详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="业主详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <ShopOwnerDetail v-if="detailDialogVisible" :owner-id="selectedOwnerId" />
    </el-dialog>

    <!-- 业主表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <ShopOwnerForm 
        v-if="formDialogVisible && formMode === 'add'" 
        :owner-id="selectedOwnerId"
        :mode="formMode"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />
      <ShopOwnerEditForm 
        v-if="formDialogVisible && formMode === 'edit'" 
        :owner-id="selectedOwnerId"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete 
} from '@element-plus/icons-vue'
import ShopOwnerDetail from './components/ShopOwnerDetail.vue'
import ShopOwnerForm from './components/ShopOwnerForm.vue'
import ShopOwnerEditForm from './components/ShopOwnerEditForm.vue'
import { shopOwnerApi } from '@/api/shop-owner'
import { shopApi } from '@/api/shop'
import type { ShopOwnerDetail as ShopOwnerDetailType, ShopOwnerQueryParams, ShopDetail } from '@/api/shop-owner'

// 响应式数据
const loading = ref(false)
const ownerList = ref<ShopOwnerDetailType[]>([])
const shopList = ref<ShopDetail[]>([])
const selectedRows = ref<ShopOwnerDetailType[]>([])

// 搜索表单
const searchForm = reactive({
  shopId: null as number | null,
  ownerType: null as number | null,
  ownerName: '',
  ownerPhone: '',
  ownerIdCard: '',
  companyName: '',
  email: '',
  status: null as number | null,
  keyword: '',
  createTimeRange: null as [string, string] | null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const selectedOwnerId = ref<number | null>(null)
const formMode = ref<'add' | 'edit'>('add')

// 计算属性
const formTitle = computed(() => {
  return formMode.value === 'add' ? '新增业主' : '编辑业主'
})

// 生命周期
onMounted(() => {
  loadOwnerList()
  loadShopList()
})

// 方法
const loadOwnerList = async () => {
  loading.value = true
  try {
    const params: ShopOwnerQueryParams = {
      current: pagination.current,
      size: pagination.size,
      ownerName: searchForm.ownerName || undefined,
      ownerType: searchForm.ownerType || undefined,
      ownerPhone: searchForm.ownerPhone || undefined,
      ownerIdCard: searchForm.ownerIdCard || undefined,
      companyName: searchForm.companyName || undefined,
      email: searchForm.email || undefined,
      status: searchForm.status || undefined,
      keyword: searchForm.keyword || undefined,
      createTimeStart: searchForm.createTimeRange?.[0] || undefined,
      createTimeEnd: searchForm.createTimeRange?.[1] || undefined
    }
    
    const response = await shopOwnerApi.getShopOwnerPage(params)
    
    if (response.code === 200) {
      ownerList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '加载业主列表失败')
    }
  } catch (error) {
    ElMessage.error('加载业主列表失败')
    console.error('加载业主列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadShopList = async () => {
  try {
    const response = await shopApi.getShopPage({
      current: 1,
      size: 100, // 获取店铺用于下拉选择，限制在100以内
      status: 1 // 只获取启用的店铺
    })
    
    if (response.code === 200) {
      shopList.value = response.data.records
    } else {
      console.warn('加载店铺列表失败:', response.message)
    }
  } catch (error) {
    console.error('加载店铺列表失败:', error)
  }
}


const handleSearch = () => {
  pagination.current = 1
  loadOwnerList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    shopId: null,
    ownerType: null,
    ownerName: '',
    ownerPhone: '',
    ownerIdCard: '',
    companyName: '',
    email: '',
    status: null,
    keyword: '',
    createTimeRange: null
  })
  handleSearch()
}

const handleAdd = () => {
  selectedOwnerId.value = null
  formMode.value = 'add'
  formDialogVisible.value = true
}

const handleEdit = (row: ShopOwnerDetailType) => {
  selectedOwnerId.value = row.id
  formMode.value = 'edit'
  formDialogVisible.value = true
}

const handleView = (row: ShopOwnerDetailType) => {
  selectedOwnerId.value = row.id
  detailDialogVisible.value = true
}

const handleDelete = async (row: ShopOwnerDetailType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除业主"${row.ownerName}"吗？删除后不可恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    loading.value = true
    const response = await shopOwnerApi.deleteShopOwner(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadOwnerList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  } finally {
    loading.value = false
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleRefresh = () => {
  loadOwnerList()
}

const handleSelectionChange = (selection: ShopOwnerDetailType[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadOwnerList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadOwnerList()
}

const handleFormSuccess = () => {
  formDialogVisible.value = false
  loadOwnerList()
  ElMessage.success(formMode.value === 'add' ? '新增成功' : '编辑成功')
}

const handleFormCancel = () => {
  formDialogVisible.value = false
}

// 工具方法
const maskIdCard = (idCard?: string) => {
  if (!idCard) return '-'
  if (idCard.length < 8) return idCard
  return idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4)
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.shop-owner-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.operation-area {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 16px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
